const Koa = require("koa");
const path = require("path");
const { sep } = path;
const env = require("./env");
const middlewareLoader = require("./loader/middleware");
const routerSchemaLoader = require("./loader/router-schema");
const routerLoader = require("./loader/router");
const controllerLoader = require("./loader/controller");
const serviceLoader = require("./loader/service");
const configLoader = require("./loader/config");
const extendLoader = require("./loader/extend");

module.exports = {
  /**
   * 启动项目
   * @param options 项目配置
   * option ={
   *  name //项目名称
   *  homePath //项目首页
   * }
   */
  start(options = {}) {
    const app = new Koa();
    app.options = options;
    app.baseDir = process.cwd(); //基础路径 项目的根路径
    app.businessPath = path.resolve(app.baseDir, `.${sep}app`); //业务路径
    app.env = env();
    // 注册日志
    console.log(`-- [start] env: ${app.env.get()} --`);
    //加载middleware
    middlewareLoader(app);
    console.log(`-- [start] load middleware done --`);
    //加载routerSchema
    routerSchemaLoader(app);
    console.log(`-- [start] load routerSchema done --`);
    //加载controller
    controllerLoader(app);
    console.log(`-- [start] load controller done --`);
    //加载service
    serviceLoader(app);
    console.log(`-- [start] load service done --`);
    //加载config
    configLoader(app);
    console.log(`-- [start] load config done --`);
    //加载extend
    extendLoader(app);
    console.log(`-- [start] load extend done --`);
    //注册全局中间件
    try {
      require(`${app.businessPath}${sep}middleware.js`)(app);
      console.log(`-- [start] load appMiddleware done --`);
    } catch (e) {
      console.log(`[exception] there is no middleware file.`);
    }

    // 注册陆游
    routerLoader(app);
    console.log(`-- [start] load router done --`);
    try {
      const port = process.env.PORT || 8080;
      const host = process.env.IP || "0.0.0.0";
      app.listen(port, host);
      console.log(`Server runing on port: ${port}`);
    } catch (error) {
      console.log(error);
    }
  },
};
